package net.hn.hnms.biz.fuel.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.hn.hnms.biz.common.jpa.utils.HqlUtils;
import net.hn.hnms.biz.common.jpa.utils.ResponsePage;
import net.hn.hnms.biz.fuel.dao.FuelRepository;
import net.hn.hnms.biz.fuel.entity.Fuel;
import net.hn.hnms.sys.common.core.constant.MineBaseConstants;
import net.hn.hnms.sys.common.core.domain.R;
import net.hn.hnms.sys.common.satoken.config.AutoSetMineCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;

/**
 * Author: PanSX
 * Date: 2023/7/4 15:29
 */
@RestController
@RequestMapping("fuel")
@Api(value = "废油处置", tags = {"废油处置"})
public class FuelController {
    @Autowired
    private FuelRepository fuelRepository;
    @Autowired
    private EntityManager entityManager;

    @PostMapping("addOrUpdate")
    @ApiOperation("添加或修改")
    @AutoSetMineCode
    public R addOrUpdate(@RequestBody @Validated Fuel fuel) {
        MineBaseConstants.Mine mine = MineBaseConstants.mineMap.get(fuel.getMineCode());
        fuel.setCompanyCode(mine.getCompanyCode());
        Fuel save = fuelRepository.save(fuel);
        return R.ok(save);
    }

    @DeleteMapping("delete")
    @ApiOperation("删除")
    public R addOrUpdate(Long id) {
        fuelRepository.deleteById(id);
        return R.ok();
    }

    @GetMapping("page")
    @ApiOperation("列表查询")
    public R<ResponsePage<Fuel>> page(Fuel fuel, @RequestParam(defaultValue = "0") int pageNum,
                                      @RequestParam(defaultValue = "20") int pageSize) {
        StringBuilder sb = new StringBuilder(" ");
        if (StringUtils.isNotBlank(fuel.getBeginTime())) {
            sb.append(" and  disposalTime >='").append(fuel.getBeginTime()).append("' ");
        }
        if (StringUtils.isNotBlank(fuel.getBeginTime())) {
            sb.append(" and disposalTime <='").append(fuel.getEndTime()).append("' ");
        }
        Pageable of = PageRequest.of(pageNum, pageSize);
        ResponsePage<Fuel> rp = HqlUtils.findPage(entityManager, fuel,
                of, sb.toString(), Sort.by(Sort.Direction.DESC, "disposalTime"));
        for (Fuel fuel1 : rp.getPageData()) {
            MineBaseConstants.Mine mine = MineBaseConstants.mineMap.get(fuel1.getMineCode());
            if (mine != null) {
                fuel1.setMineName(mine.getMineName());
                fuel1.setCompanyName(mine.getCompanyName());
            }
        }
        return R.ok(rp);
    }
}
